import json
from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from apps.oauth.models import OAuthQQUser, OAuthSinaUser
from apps.users.models import User
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE
from QQLoginTool.QQtool import OAuthQQ
from utils import sinaweibopy3


# 判断是否绑定openid
def is_bind_openid(openid, request):
    # 判断openid在不在QQ登录表OAuthQQUser
    try:
        qq_user = OAuthQQUser.objects.get(openid=openid)

    except OAuthQQUser.DoesNotExist:
        # 不存在--跳转到绑定页面
        context = {'openid': openid}
        response = render(request, 'oauth_callback.html', context)

    else:
        # 存在
        user = qq_user.user
        login(request, user)
        # 1.保持登录状态
        # 2.cookie保存用户名
        # 3.重定向到首页
        response = redirect(reverse('content:index'))
        response.set_cookie('username', user.username, max_age=14*24*3600)
    return response


class QQLoginView(View):
    # QQ登录网址
    def get(self, request):
        # 1.导包
        # 2.实例化对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=None)
        login_url = oauth.get_qq_url()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})


class QQOauthCallbackView(View):
    def get(self, request):
        # 1.code request.GET.get
        code = request.GET.get('code')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)
        # 2.code-->access_token
        token = oauth.get_access_token(code)
        # 3.access_token--->openid
        openid = oauth.get_open_id(token)
        # 4.判断是否绑定openid
        response = is_bind_openid(openid, request)
        return response


# 微博登录
class WeiboLoginView(View):
    def get(self, request):
        client = sinaweibopy3.APIClient(
            # app_key： app_key值
            app_key=settings.APP_KEY,
            # app_secret：app_secret 值
            app_secret=settings.APP_SECRET,
            # redirect_uri ： 回调地址
            redirect_uri=settings.REDIRECT_URL
        )
        login_url = client.get_authorize_url()
        return http.JsonResponse({"code": 0, "errmsg": "OK", "login_url": login_url})


class BangdingView(View):
    def get(self, request):
        # 获取code
        code = request.GET.get('code')
        client = sinaweibopy3.APIClient(
            # app_key： app_key值
            app_key=settings.APP_KEY,
            # app_secret：app_secret 值
            app_secret=settings.APP_SECRET,
            # redirect_uri ： 回调地址
            redirect_uri=settings.REDIRECT_URL
        )
        # 2.根据code值获取access_token和uid值
        result = client.request_access_token(code)
        access_token = result.access_token
        uid = CookieSecret.dumps(result.uid)
        # 3.判断 美多后台是否绑定了 uid; 如果绑定跳转到首页--没有绑定跳转到绑定页面(sina_callback.html)
        try:
            sina_user = OAuthSinaUser.objects.get(uid=uid)
        except OAuthSinaUser.DoesNotExist:
            # 不存在--绑定页面(sina_callback.html)--带着uid
            return render(request, 'sina_callback.html', context={'uid': uid})

        user = sina_user.user
        # 保持登录状态
        login(request, user)
        # 设置首页用户名
        response = redirect(reverse('contents:index'))
        response.set_cookie(request, 'sina_callback.html', max_age=3600*24*14)

        return response


class BangPushView(View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        sms_code = json_dict.get('sms_code')
        uid = json_dict.get('uid')

        if not uid:
            return render(request, 'sina_callback.html', {'uid_errmsg': '无效的uid'})

        from django_redis import get_redis_connection
        redis_code_client = get_redis_connection('sms_code')
        redis_code = redis_code_client.get('sms_%s' % mobile)
        print(sms_code)

        if redis_code is None:
            return render(request, 'sina_callback.html', {'sms_code_errmsg': '无效的短信验证码'})

        if sms_code != redis_code.decode():
            return render(request, 'sina_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})

        # 保存注册数据
        try:
            user = User.objects.get(mobile=mobile)

        except User.DoesNotExist:
            # 用户不存在新建用户
            user = User.objects.create_user(username=mobile, password=password, mobile=mobile)

            # 如果用户存在，检查用户密码
            if not user.check_password(password):
                return render(request, 'sina_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 绑定用户
        OAuthSinaUser.objects.create(
            uid=uid,
            user=user
        )

        # 保持登录状态
        login(request, user)

        response = http.JsonResponse({'status': 5000})
        response.set_cookie('username', user.username, max_age=3600*24*14)
        return response
